package household.base;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class IBaseDAOImpl<M> implements IBaseDAO<M>{
	
	@Autowired
	public SessionFactory sessionFactory;
	
	private Class<M> entityClass;
	
	@SuppressWarnings("unchecked")
	public IBaseDAOImpl(){
		entityClass = (Class<M>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public int save(M model) {
		getCurrentSession().save(model);
		try {
			Field field =model.getClass().getDeclaredField("id");
			field.setAccessible(true);
			int id = field.getInt(model);
			return id;
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;		
	}

	public boolean delete(int id) {
		M m = get(id);
		try {
			getCurrentSession().delete(m);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean update(M model) {
		try {
			getCurrentSession().update(model);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	public M get(int id) {
		return (M) getCurrentSession().get(entityClass, new Integer(id));
	}	
	
	public Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}

}
